using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace AppManagement.MainManagers
{
	#region using
	using DevComponents.DotNetBar;
	using AppManagement.Models;
	using AppManagement.Repositories;
	using AppManagement.Helpers;
	using System.Data;
	using System.Drawing;
	using System.IO;
	#endregion

	public partial class FrmLapKeHoachDaoTao : Office2007Form
	{
		public EventHandler Handler { get; set; }
		private DataTable DataSource;
		private int MaKHDT;
		private DevComponents.DotNetBar.Controls.TextBoxX txtMaCN;

		public FrmLapKeHoachDaoTao(int macn, int makhdt = -1)
		{
			InitializeComponent();
            InitGridView();
            InitHiddenFields();
			MaKHDT = makhdt;
            txtMaCN.Text = macn.ToString();
            txtChuyenNganh.Text = ChuyenNganhRepository.SelectByID(macn).TenCN;
            txtKhoa.Text = ChuyenNganhRepository.SelectByID(macn).Khoa.TenKhoa;
		}

		private void FrmLapKeHoachDaoTao_Load(object sender, EventArgs e)
		{
			InitDataSource();
			if (MaKHDT != -1)
			{
				LoadKeHoachDaoTao();
			}
		}

		private void InitGridView()
		{
			DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "MaHP",
				DataPropertyName = "MaHP",
				Name = "MaHP",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/2))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "TenHP",
				DataPropertyName = "TenHP",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/2)) - 1
			};
			dtgvData.Columns.Add(objColumn);
		}

		public void InitHiddenFields()
		{
			txtMaCN = new DevComponents.DotNetBar.Controls.TextBoxX
			{
				Name = "txtMaCN",
				Text = ""
			};
			txtMaCN.Visible = false;
		}

		public void InitDataSource()
		{
			DataSource = new DataTable();
			DataSource.Columns.Add("MaHP");
			DataSource.Columns.Add("TenHP");
			DataSource.Columns.Add("");
			DataView objTimeSheetDV = new System.Data.DataView(DataSource);
			objTimeSheetDV.AllowNew = false;
			dtgvData.AutoGenerateColumns = false;
			dtgvData.DataSource = objTimeSheetDV;
			dtgvData.ClearSelection();
		}

		public void GetChuyenNganh(object sender, EventArgs e)
		{
			var eventType = (TransferSimpleDataEvent)e;
			string[] comp = eventType.Data.Split(new char[] { '#' });
			txtMaCN.Text = comp[0];
			txtChuyenNganh.Text = comp[1];
		}


		private void btnThem_Click(object sender, EventArgs e)
		{
            var makhoa = ((ChuyenNganh)ChuyenNganhRepository.SelectByID(int.Parse(this.txtMaCN.Text))).MaKhoa.Value;
            FrmCapNhatChiTietKHDT frm = new FrmCapNhatChiTietKHDT(makhoa);
			frm.Handler += GetChiTietKHDT;
			frm.ShowDialog();
		}

		public void GetChiTietKHDT(object sender, EventArgs e)
		{
			var eventType = (TransferSimpleDataEvent)e;
			string[] comp = eventType.Data.Split(new char[] { '#' });
            var item = HocPhanRepository.SelectByID(int.Parse(comp[0]));
			if(item != null)
			{
				DataSource.Rows.Add(item.MaHP, item.TenHP);
			}
		}


		private void btnXoa_Click(object sender, EventArgs e)
		{
			if (DataSource.Rows.Count > 0)
			{
				DataSource.Rows.RemoveAt(dtgvData.SelectedRows[0].Index);
			}
		}

		private bool ValidateInput(ref string errorText)
		{
            if (string.Empty.Equals(txtTenGoi.Text))
            {
                errorText = "Bạn chưa nhập tên gọi";
                return false;
            }
            if (string.Empty.Equals(txtNamHoc.Text))
            {
                errorText = "Bạn chưa nhập năm học";
                return false;
            }
            if (string.Empty.Equals(txtHocKy.Text))
            {
                errorText = "Bạn chưa nhập học kỳ";
                return false;
            }
			if (DataSource.Rows.Count == 0)
			{
				errorText = "Danh sách hiện thời không có gì!";
				return false;
			}
			return true;
		}

		private void btnCapNhat_Click(object sender, EventArgs e)
		{
			var errorText = "";
			bool success = false;
			if (!ValidateInput(ref errorText))
			{
				MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			if (ActionUpdate())
			{
				success = true;
			}
			if (success)
			{
				MessageBoxEx.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			else
			{
				MessageBoxEx.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btnThoat_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private bool ActionUpdate()
		{
			try
			{
				DataContext.Instance.Connection.Open();
				using (var transaction = DataContext.Instance.Connection.BeginTransaction())
				{
					var kehoachdaotao = new KeHoachDaoTao
					{
						MaCN = int.Parse(txtMaCN.Text),
						TenGoi = txtTenGoi.Text,
						NamHoc = int.Parse(txtNamHoc.Text),
						HocKy = int.Parse(txtHocKy.Text),
					};
                    if (!string.Empty.Equals(txtTuanBatDau.Text))
                    {
                        kehoachdaotao.TuanBatDau = int.Parse(txtTuanBatDau.Text);
                    }
                    if (!string.Empty.Equals(txtTuanThi.Text))
                    {
                        kehoachdaotao.TuanThi = int.Parse(txtTuanThi.Text);
                    }
					if (KeHoachDaoTaoRepository.Insert(kehoachdaotao))
					{
						for (int i = 0; i <= DataSource.Rows.Count - 1; i++)
						{
							var chitietkhdt = new ChiTietKHDT
							{
								MaKHDT = kehoachdaotao.MaKHDT,
								MaHP = int.Parse(DataSource.Rows[i]["MaHP"].ToString()),
							};
							if (!ChiTietKHDTRepository.Insert(chitietkhdt))
							{
								DataContext.Instance.Connection.Close();
								return false;
							}
						}
						transaction.Commit();
					}
					else
					{
						DataContext.Instance.Connection.Close();
						return false;
					}
				}
				DataContext.Instance.Connection.Close();
				return true;
			}
			catch
			{
				DataContext.Instance.Connection.Close();
				return false;
			}
		}

		private void LoadKeHoachDaoTao()
		{
			var kehoachdaotao = KeHoachDaoTaoRepository.SelectByID(MaKHDT);
			if (kehoachdaotao != null)
			{
				txtMaKHDT.Text = MaKHDT.ToString();
				txtMaCN.Text = kehoachdaotao.MaCN.ToString();
				txtChuyenNganh.Text = kehoachdaotao.ChuyenNganh.TenCN;
				txtTenGoi.Text = kehoachdaotao.TenGoi.ToString();
				txtNamHoc.Text = kehoachdaotao.NamHoc.ToString();
				txtHocKy.Text = kehoachdaotao.HocKy.ToString();
				txtTuanBatDau.Text = kehoachdaotao.TuanBatDau.ToString();
				txtTuanThi.Text = kehoachdaotao.TuanThi.ToString();
				LoadChiTietKHDT(kehoachdaotao);
			}
		}

		private void LoadChiTietKHDT(KeHoachDaoTao kehoachdaotao)
		{
			var lst = ChiTietKHDTRepository.SelectByMaKHDT(kehoachdaotao.MaKHDT);
			if (lst.Count > 0)
			{
				foreach (var item in lst)
				{
					DataSource.Rows.Add(item.MaHP, item.HocPhan.TenHP);
				}
			}
		}

        private void FrmLapKeHoachDaoTao_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Handler(sender, e);
        }

	}

}
